import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class PhoneNumberEditor extends JPanel {

    JLabel label;
    JTextField text;
    static JComponent demo;

    public PhoneNumberEditor() {
        label = new JLabel("Write Java code");
        text = new JTextField(30);
        Document phoneDocument = new PhonePlainDocument();
        text.setDocument(phoneDocument);
        add(label);
        add(text);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TextFieldDemo");

        demo = new PhoneNumberEditor();

        frame.add(demo);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[ ] args) {
        createAndShowGUI();
    }
}
//te: For marking purpose only, the answer preload extends MockPlainDocument
class PhonePlainDocument extends PlainDocument {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (offs >= 12) {
            return;
        }
        try {
            Integer number = Integer.parseInt(str);
            super.insertString(offs , str, a);
            if (offs == 1 || offs == 4) {
                super.insertString(offs + 1, "-", a);
            }
        } catch (Exception e) {
        }
    }
}